<template>
  <div>
    <el-button type="primary" size="small" @click="hanldeAddAddress" style="margin-bottom: 10px">{{
      $t('mall.add')
    }}</el-button>
    <el-table :data="addAddressList" serial>
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :class-name="item.width > 60 ? 'column' : ''"
        show-overflow-tooltip
        :formatter="formatter"
      >
        <template #default="{ row: { country, province, city, zone } }">
          <div v-if="item.prop === 'region'">
            {{ country }} {{ province }} {{ city }} {{ zone }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('coommon.operation')"
        align="center"
        width="250"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            v-if="tableSelection"
            @click="selectAddress(scope.row)"
          >
            {{ $t('smt.Define') }}
          </el-button>
          <el-button size="small" type="primary" link @click="setDefault(scope.row)">
            {{ $t('smt.Settingthedefaultaddress') }}
          </el-button>
          <el-button size="small" type="primary" link @click="editAddress(scope.row.id)">
            {{ $t('mall.modify') }}
          </el-button>
          <el-button size="small" type="danger" link @click="deleteAddressInfo(scope.row.id)">
            {{ $t('smt.Deleting') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      class="m-b-10 right-align"
      v-show="queryParams.totalRow > 0"
      :total="queryParams.totalRow"
      v-model:page="queryParams.pageNumber"
      v-model:limit="queryParams.pageSize"
      @pagination="handlePaginationChange"
    />
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      width="600"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 400px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item :label="`${$t('mall.recipient_name')}:`" prop="name">
          <el-input v-model="ruleForm.name" :placeholder="`${$t('mall.enter_recipient_name')}`" />
        </el-form-item>
        <el-form-item :label="`${$t('mall.mobile_number')}:`" prop="phone" class="phone-check">
          <div style="display: flex; flex-direction: row">
            <el-select v-model="ruleForm.areaCode" placeholder="请选择" style="width: 160px">
              <el-option
                v-for="item in countryCode"
                :key="item.zone"
                :label="`${isZhcnOrEn ? item.cn : item.en} +${item.zone}`"
                :value="item.code"
              >
              </el-option>
            </el-select>
            <div style="width: 10px"></div>
            <el-input
              v-model="ruleForm.phone"
              style="width: 190px"
              :placeholder="`${$t('mall.enter_mobile_number')}`"
            />
          </div>
        </el-form-item>
        <el-form-item :label="`${$t('mall.region')}:`" prop="region">
          <el-cascader
            :placeholder="`${$t('mall.enter_your_region')}`"
            :props="cascadeProps"
            v-model="ruleForm.region"
            style="width: 318px"
          />
        </el-form-item>
        <el-form-item :label="`${$t('mall.shipping_address')}:`" prop="address">
          <el-input v-model="ruleForm.address" :placeholder="$t('mall.detailed_address_info')" />
        </el-form-item>
        <el-form-item :label="`${$t('mall.postal_code')}:`" prop="code">
          <el-input v-model="ruleForm.code" :placeholder="$t('mall.enter_postal_code')" />
        </el-form-item>
        <el-checkbox
          v-model="ruleForm.isMain"
          :label="`${$t('mall.default_address')}`"
          size="large"
          :false-label="1"
          :true-label="2"
          style="margin-left: 95px"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">{{ $t('smt.Cancel') }}</el-button>
          <el-button type="primary" @click="saveAddress(ruleFormRef)">
            {{ $t('om.Save') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  listAddress,
  provincesCitiesAndDistricts,
  addAddress,
  deleteAddress,
  inquireAddress,
  updateAddress,
} from '@/server/api/biz.js';
import { ref, onMounted, reactive, computed, watchEffect, defineExpose } from 'vue';
import countryCode from './areaCode.js';
import { useI18n } from 'vue-i18n';
import useAppStore from '@/store/modules/app';
import { debounce } from 'lodash';

const appStore = useAppStore();

const { t } = useI18n();
const title = ref('');
const dialogVisible = ref(false);
const ruleFormRef = ref(null);
const addAddressList = ref();
const queryParams = reactive({
  pageNumber: 1,
  pageSize: 10,
  totalRow: 0,
});
const ruleForm = ref({
  addressType: 2,
  useType: 1,
  code: '',
  areaCode: 'CN',
  isMain: 1,
  houseCode: '0',
  lastName: '0',
  eoriTaxNumber: '0',
  customerId: '0',
  customerAccountId: '0',
  companyName: '0',
});
let regionForm = reactive({
  level: '1',
  parentCode: '0',
  parentId: '0',
});
const regionData = ref();

const emit = defineEmits(['selected', 'close']);

const isZhcnOrEn = ref(true);

const validateMobile = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('mall.enter_mobile_number')));
  } else if (!/^\d{8,11}$/.test(value)) {
    callback(new Error(t('mall.valid_mobile_number')));
  } else {
    callback();
  }
};

const rules = reactive({
  name: [
    {
      required: true,
      message: t('mall.enter_recipient_name'),
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: t('mall.valid_mobile_number'),
      trigger: 'blur',
      validator: validateMobile,
    },
  ],
  region: [
    {
      required: true,
      message: t('mall.enter_your_region'),
      trigger: 'change',
    },
  ],
  address: [
    {
      required: true,
      message: t('mall.enter_the_shipping_addres'),
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: t('mall.enter_postal_code'),
      trigger: 'blur',
    },
  ],
});

const columns = computed(() => [
  {
    label: t('mall.recipient'),
    prop: 'name',
    align: 'center',
    width: '110px',
  },
  {
    label: t('mall.mobile_number'),
    prop: 'phone',
    align: 'center',
    width: '130px',
  },
  {
    label: t('mall.region'),
    align: 'center',
    prop: 'region',
    width: '250px',
  },
  {
    label: t('mall.shipping_address'),
    align: 'center',
    prop: 'address',
    width: '170px',
  },
  {
    label: t('mall.postal_code'),
    prop: 'code',
    align: 'center',
    width: '90px',
  },
  {
    label: t('mall.default_address'),
    align: 'center',
    prop: 'isMain',
    width: '110px',
  },
  // {
  //   label: '操作',
  //   align: 'center',
  //   width: '330px',
  //   type: 'btn',
  // },
]);

defineProps(['tableSelection']);

const cascadeProps = ref();

const formatter = (row, column) => {
  if (column.property === 'isMain') {
    return {
      1: t('mall.no'),
      2: t('mall.yes'),
    }[row[column.property]];
  } else {
    return row[column.property];
  }
};

// 保存数据
const saveAddress = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      const [country, province, city, zone] = ruleForm.value.region;
      // 区号
      const areaCode = countryCode.find((item) => item.code === ruleForm.value.areaCode);

      ruleForm.value.country = country;
      ruleForm.value.province = province;
      ruleForm.value.city = city || '';
      ruleForm.value.zone = zone || '';

      if (!ruleForm.value.id) {
        const { code } = await addAddress({
          ...ruleForm.value,
          phone: `${areaCode.zone} ${ruleForm.value.phone}`,
        });
        if (code === 200) {
          ElMessage({
            type: 'success',
            message: t('mall.added_successfully'),
          });
          getAddressList();
          handleClose();
        } else {
          ElMessage({
            type: 'error',
            message: t('mall.add_address_failed'),
          });
        }
      } else {
        if (!areaCode) {
          ElMessage({
            type: 'error',
            message: t('mall.area_code_cannot_be_empty'),
          });
          return;
        }
        const { code } = await updateAddress({
          ...ruleForm.value,
          phone: `${areaCode.zone} ${ruleForm.value.phone}`,
        });
        if (code === 200) {
          ElMessage({
            type: 'success',
            message: t('mall.modification_successful'),
          });
          getAddressList();
          handleClose();
        } else {
          ElMessage({
            type: 'error',
            message: t('mall.edit_address_failed'),
          });
        }
      }
    }
  });
};

// 防抖设置默认地址
const debouncedMethod = debounce(async (row) => {
  const { code } = await updateAddress(row);
  if (code === 200) {
    ElMessage({
      type: 'success',
      message: t('mall.set_success'),
    });
    getAddressList();
  } else {
    ElMessage({
      type: 'error',
      message: t('mall.set_default_failed'),
    });
  }
}, 500); // 设置延迟时间，单位为毫秒

// 设为默认
const setDefault = async (row) => {
  row.isMain = 2;

  debouncedMethod(row);
};

const handleClose = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
};

// 删除地址
const deleteAddressInfo = (id) => {
  ElMessageBox.confirm(t('smt.deletethecurrentaddress'), '', {
    confirmButtonText: t('smt.Define'),
    cancelButtonText: t('smt.Cancel'),
    type: 'warning',
  })
    .then(() => {
      deleteAddress(encodeURIComponent(id)).then((res) => {
        if (res.code === 200) {
          getAddressList();
          ElMessage({
            type: 'success',
            message: t('mall.delete_successful'),
          });
        }
      });
    })
    .catch(() => {});
};

// 获取省市区数据
const initProvincesCitiesAndDistricts = async () => {
  const { data } = await provincesCitiesAndDistricts(regionForm);
  regionData.value = data;
  cascadeProps.value = {
    lazy: true,
    lazyLoad(node, resolve) {
      let { level } = node;
      setTimeout(() => {
        // 是提前接口获取的一级下拉框
        if (level === 0) {
          let nodes;
          if (regionData?.value?.length) {
            nodes = regionData.value.map((i) => {
              const { name, code, id } = i;
              return {
                value: name,
                label: name,
                parentCode: code,
                parentId: id,
              };
            });
          } else {
            nodes = [];
          }

          resolve(nodes);
        }

        if (level === 1) {
          regionForm = {
            level: '2',
            parentCode: node.data.parentCode,
            parentId: node.data.parentId,
          };
          provincesCitiesAndDistricts(regionForm).then(({ data }) => {
            const nodes = data.map((i) => {
              const { name, code, id, zipCode } = i;
              return {
                value: name,
                label: name,
                parentCode: code,
                parentId: id,
                zipCode,
                leaf: code === null ? node.level >= 1 : node.level >= 3,
              };
            });
            resolve(nodes);
          });
        }
        if (level === 2) {
          const { parentCode, parentId, zipCode } = node.data;
          regionForm = {
            level: '3',
            parentCode,
            parentId,
          };
          if (!ruleForm.value.id) {
            ruleForm.value.code = zipCode;
          }
          provincesCitiesAndDistricts(regionForm).then(({ data }) => {
            const nodes = data.map((i) => {
              const { name, code, id, zipCode } = i;
              return {
                value: name,
                label: name,
                zipCode,
                parentCode: code,
                parentId: id,
              };
            });
            resolve(nodes);
          });
        }
        if (level === 3) {
          const { parentCode, parentId, zipCode } = node.data;

          regionForm = {
            level: '4',
            parentCode,
            parentId,
          };
          if (!ruleForm.value.id) {
            ruleForm.value.code = zipCode;
          }

          provincesCitiesAndDistricts(regionForm).then(({ data }) => {
            const nodes = data.map((i) => {
              const { name, code, id, zipCode } = i;
              return {
                value: name,
                label: name,
                parentCode: code,
                parentId: id,
                zipCode,
                leaf: node.level >= 1,
              };
            });
            resolve(nodes);
          });
        }
      }, 500);
    },
  };
};

const hanldeAddAddress = () => {
  dialogVisible.value = true;
  title.value = t('mall.add_shipping_information');
  ruleForm.value.id = null;
  ruleForm.value.areaCode = 'CN';
};

const editAddress = async (id) => {
  dialogVisible.value = true;
  title.value = t('mall.edit_shipping_information');

  const { data, code, msg } = await inquireAddress({ id });
  if (code !== 200) {
    ElMessage({
      type: 'error',
      message: msg,
    });
    return;
  }
  const { zone, province, country, city, phone } = data;
  let parts = phone.split(' ');

  ruleForm.value = data;
  if (parts[1]) {
    ruleForm.value.phone = parts[1]; // 手机号
  } else {
    ruleForm.value.phone = phone;
  }

  const areaIsCode = countryCode.find((item) => item.zone === parts[0]);
  // 全球区号
  if (areaIsCode) {
    ruleForm.value.areaCode = areaIsCode.code;
  }
  if (!city) {
    ruleForm.value.region = [country, province];
  } else {
    ruleForm.value.region = [country, province, city, zone];
  }
};

// 获取地址信息
const getAddressList = (page = 1, limit = 10) => {
  const obj = {
    useType: 1,
    current: page,
    pageSize: limit,
  };
  listAddress(obj).then((res) => {
    if (res.code === 200) {
      const { records, total } = res.data;
      addAddressList.value = records;
      queryParams.totalRow = Number(total);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 分页
 * @param {*} page
 * @param {*} limit
 */
const handlePaginationChange = (page = 1, limit = 10) => {
  getAddressList(page, limit);
};

const selectAddress = (item) => {
  emit('selected', item);
};

onMounted(() => {
  initProvincesCitiesAndDistricts();
  getAddressList();
});

watchEffect(() => {
  if (appStore.language === 'zhCN') {
    isZhcnOrEn.value = true;
  } else {
    isZhcnOrEn.value = false;
  }
});
</script>
<style lang="scss" scoped>
.right-align {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.phone-check ::v-deep .el-form-item__error {
  margin-left: 175px;
  width: 200px;
}
</style>
